/*
 * @Author: wuqiang
 * @Date: 2023-07-13 22:38:01
 * @LastEditors: wuqiang
 * @LastEditTime: 2023-11-17 11:24:39
 */
import { RELATIONS } from '@/constants'
import {
  getAge,
  getStartInsuranceDate,
  getStopInsuranceDate,
  isValidIdCard,
  isValidName,
  isValidPhone
} from '@/utils'
import { ActionSheet, ActivityIndicator, Switch, Toast } from 'antd-mobile'
import React, { useEffect, useReducer, useState } from 'react'
import { useLocation, useHistory } from 'react-router-dom'
import { API } from '../redCard/common/api'
import './index.scss'

const relations = {
  '10': '本人',
  '20': '配偶',
  '30': '子女',
  '40': '父母'
}

const RedCardConfirm = () => {
  const history = useHistory()
  const location = useLocation()
  const [info] = useState<any>(() => {
    return location.state || {}
  })
  const [loading, setLoading] = useState(false)
  const [backup, setBackup] = useReducer((oldValue, newValue) => {
    return { ...oldValue, ...newValue }
  }, {})
  const [sumPremium, setSumPremium] = useState('')

  if (!Object.keys(info)?.length) {
    history.push('/redCard')
  }
  console.log('location.state =>', location.state)

  const calculate = async () => {
    const [code, data] = await API.post('/insurance/premium/calculate', {...info, callbackUrl: 'https://www.baidu.com'})

    if (code === 200) {
      setSumPremium(((parseInt(data?.sumPremium) || 0) / 100).toFixed(2))
    } else {
      Toast.fail(data || '出错了', 2, undefined, false);
    }
  }

  const submit = async () => {
    if (loading) {
      Toast.fail('不能重复请求', 2, undefined, false);
      return;
    }
    if (!isValidName(backup.name)) {
      Toast.fail('备选联系人姓名必须为2位以上非空字符', 2, undefined, false)
      return
    }

    if (!backup.relation) {
      Toast.fail('请选择备选联系人与投保人的关系', 2, undefined, false)
      return
    }

    if (!isValidPhone(backup.mobile)) {
      Toast.fail('备选联系人电话格式不正确', 2, undefined, false)
      return
    }

    setLoading(true)

    const [code, data] = await API.post('/insurance/insure', {
      ...info,
      backup
    })
    setLoading(false);
    if (code === 200) {
      window.location.href = data?.payUrl;
    } else {
      Toast.fail(data || '出错了', 2, undefined, false);
    }
  }

  const showActionSheet = param => {
    const BUTTONS = Object.keys(RELATIONS)
    ActionSheet.showActionSheetWithOptions(
      {
        options: BUTTONS,
        maskClosable: true
      },
      buttonIndex => {
        setBackup({
          relation: RELATIONS[BUTTONS[buttonIndex]]
        })
      }
    )
  }

  useEffect(() => {
    calculate()
  }, [])
  return (
    <div className="red-card-confirm-page">
      <div className="content">
        <div className="card">
          <h2 className="section_title">投保人信息</h2>
          <div className="form">
            <div className="form_item">
              <label className="form_label">姓名：</label>
              <div className="form_value">{info?.applicant?.name}</div>
            </div>

            <div className="form_item">
              <label className="form_label">证件类型：</label>
              <div className="form_value">居民身份证</div>
            </div>

            <div className="form_item">
              <label className="form_label">证件号码：</label>
              <div className="form_value">{info?.applicant?.idNo}</div>
            </div>

            <div className="form_item">
              <label className="form_label">出生日期：</label>
              <div className="form_value">
                {info?.applicant?.idNo?.substr(6, 4)}-{info?.applicant?.idNo?.substr(10, 2)}-
                {info?.applicant?.idNo?.substr(12, 2)}
              </div>
            </div>

            <div className="form_item">
              <label className="form_label">性别：</label>
              <div className="form_value">男</div>
            </div>

            <div className="form_item">
              <label className="form_label">手机号码：</label>
              <div className="form_value">{info?.applicant?.mobile}</div>
            </div>
          </div>
        </div>

        <div className="card">
          <h2 className="section_title">备选联系方式</h2>
          <div className="form">
            <div className="form_item">
              <label className="form_label">姓名：</label>
              <div className="form_input">
                <input
                  value={backup.name}
                  onChange={e => {
                    setBackup({ name: e.target.value?.trim() })
                  }}
                />
              </div>
            </div>
            <div className="form_item" onClick={showActionSheet}>
              <label className="form_label">与投保人关系：</label>
              <div className="form_input">
                <input value={relations[backup.relation] || ''} readOnly />
              </div>
            </div>
            <div className="form_item">
              <label className="form_label">联系电话：</label>
              <div className="form_input">
                <input
                  value={backup.mobile}
                  onChange={e => {
                    setBackup({ mobile: e.target.value?.trim() })
                  }}
                />
              </div>
            </div>
          </div>
        </div>

        <div className="card">
          <h2 className="section_title">承保信息</h2>
          <div className="form">
            <div className="form_item">
              <label className="form_label">保险期限：</label>
              <div className="form_value">{getStartInsuranceDate()} 00时</div>
            </div>
            <div className="form_item">
              <label className="form_label">至：</label>
              <div className="form_value">{getStopInsuranceDate()} 24时</div>
            </div>
          </div>
        </div>

        {info?.insurants?.map((item, index) => {
          return (
            <div className="card">
              <h2 className="section_title">被保险人信息</h2>
              <div className="form">
                <div className="form_item">
                  <label className="form_label">姓名：</label>
                  <div className="form_value">{item.name}</div>
                </div>

                <div className="form_item">
                  <label className="form_label">证件类型：</label>
                  <div className="form_value">居民身份证</div>
                </div>

                <div className="form_item">
                  <label className="form_label">证件号码：</label>
                  <div className="form_value">{item.idNo}</div>
                </div>

                <div className="form_item">
                  <label className="form_label">与投保人关系：</label>
                  <div className="form_value">{relations[item.relation] || '--'}</div>
                </div>

                <div className="form_item">
                  <label className="form_label">有无社保：</label>
                  <div className="form_value">{item.socialInsuFlag ? '有' : '无'}</div>
                </div>

                <div className="form_item" style={{ height: 'auto' }}>
                  <label
                    className="form_label"
                    style={{ alignItems: 'flex-start', paddingTop: '20px' }}>
                    保险责任:
                  </label>
                  <div
                    className="form_input"
                    style={{ justifyContent: 'flex-start', flexWrap: 'wrap', padding: '10px 0' }}>
                    <Switch checked={!!item.accessorys} color="#FC8F2B" disabled />
                    {item.accessorys ? (
                      <div className="form_options">
                        <div className="form_options_item active">恶性肿瘤特药保险金</div>
                        {item.idNo && isValidIdCard(item.idNo) && (getAge(item.idNo) || 0) <= 60 ? (
                          <>
                            <div className="form_options_item active">重大疾病一次性给付金</div>
                            <div
                              className="form_options_item"
                              style={{ background: 'transparent', border: '0 none' }}>
                              {(getAge(item.idNo) || 0) <= 60 && (getAge(item.idNo) || 0) >= 0 ? (
                                <div
                                  className={`form_option_first ${
                                    item?.accessorys?.find(
                                      item =>
                                        item.code === '101304' && item.insuredAmount === 5000000
                                    )
                                      ? 'active'
                                      : ''
                                  }`}>
                                  5万
                                </div>
                              ) : null}
                              {(getAge(item.idNo) || 0) <= 45 && (getAge(item.idNo) || 0) >= 0 ? (
                                <div
                                  className={`form_option_second ${
                                    item?.accessorys?.find(
                                      item =>
                                        item.code === '101304' && item.insuredAmount === 10000000
                                    )
                                      ? 'active'
                                      : ''
                                  }`}>
                                  10万
                                </div>
                              ) : null}
                            </div>
                          </>
                        ) : null}
                        <div
                          className={`form_options_item ${
                            item?.accessorys?.find(item => item.code === '105544') ? 'active' : ''
                          }`}
                          key={index}>
                          恶性肿瘤特需责任
                        </div>
                      </div>
                    ) : null}
                  </div>
                </div>
              </div>
            </div>
          )
        })}
      </div>

      <div className="footer">
        <div className="btn">
          <span className="btn_phone">应付金额：{sumPremium}</span>
          <span className="btn_insure" onClick={submit}>
            下一步
          </span>
        </div>
      </div>

      <ActivityIndicator toast text="Loading..." animating={loading} />
    </div>
  )
}

export default RedCardConfirm
